package io.fredia.common.core.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import io.fredia.common.core.Mapper;
import io.fredia.common.core.base.Query;
import io.fredia.common.core.pager.PageModel;
import io.fredia.common.core.service.IBaseService;
import io.fredia.common.exception.BaseException;



/**
 * 业务基类
 * @author : fredia
 * @email : trumpey@163.com
 * @since : 2017年11月16日
 * @version : v0.0.1
 */
@Service
public abstract class BaseServiceImpl<T> implements IBaseService<T> {
	
	@Autowired
	private Mapper<T> mapper;
	
	@Override
	public T getByPrimaryKey(Object primaryKey) {
		return mapper.getByPrimaryKey(primaryKey);
	}

	@Override
	public T getOne(Query query) {
		List<T> list = mapper.getList(query);
		if (list == null || list.size() == 0) {
            return null;
        }
		if (list.size() == 1) {
            return list.get(0);
        } else {
            throw new BaseException(300, "期望查询一条记录，结果返回多条记录");
        }
	}

	@Override
	public List<T> getList(Query query) {
		return mapper.getList(query);
	}

	@Override
	public Integer getListCount(Query query) {
		return mapper.getListCount(query);
	}
	
	@Override
	public PageModel<T> getPageList(Query query) {
		if (query.getPageIndex() == null) {
            throw new BaseException(300, "分页查询必须设置pageIndex"); 
        }
        if (query.getPageSize() == null) {
            throw new BaseException(300, "分页查询必须设置pageSize");
        }
        
        //query.setStartIndex((query.getPageIndex() - 1) * query.getPageSize() + 1);
        //query.setEndIndex(query.getStartIndex() + query.getPageSize() - 1);
        
        if (query.getPageSize() <= 0) {
        	query.setRowstartindex(0);
        	query.setRowendindex(0);
		} else {
			query.setRowstartindex((query.getPageIndex() - 1) * query.getPageSize() + 1);
			query.setRowendindex(query.getPageSize());
		}
        
        Integer count = mapper.getListCount(query);
        List<T> resultList = mapper.getList(query);
		return new PageModel<>(resultList, query.getPageIndex(), query.getPageSize(), count);
	}

	@Override
	public T insert(T model) {
		int insertCount = mapper.insert(model);
		if (insertCount != 1) {
			throw new BaseException(300, "数据新增失败");
		}	
		return model;
	}

	@Override
	public void deleteByPrimaryKey(Object primaryKey) {
		int deleteCount = mapper.deleteByPrimaryKey(primaryKey);
		if (deleteCount != 1) {
			throw new BaseException(300, "删除数据异常");
		}
	}

	@Override
	public void updateByPrimaryKey(T model) {
		int updateCount = mapper.updateByPrimaryKey(model);
		if (updateCount != 1) {
			throw new BaseException(300, "数据更新异常");
		}
	}

	@Override
	public void updateByPrimaryKeyAll(T model) {
		int updateCount = mapper.updateByPrimaryKeyAll(model);
		if (updateCount != 1) {
			throw new BaseException(300, "数据更新异常");
		}
	}
	
}
